package com.quzi.kettle.activitise;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.R;
import com.quzi.kettle.bean.ChannelObject;
import com.quzi.kettle.push.MQTTService;
import com.quzi.kettle.push.PushCallback;
import com.quzi.kettle.push.Thermometer;
import com.quzi.kettle.utils.Base64;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.utils.NetworkStatusUtil;

public class MainActivity extends BaseActivity {

	public static final String SERVICE_CLASSNAME = "com.quzi.kettle.push.MQTTService";
	public static final int SCANQR_REQUEST = 99;
	public static final int UDP_REQUEST = 98;
	private Button button, scanQR, sendText, initEasylink;
	private LinearLayout sendLayout;
	private TextView text, scanResult, udpResult;
	private EditText mtext;
	private StringBuilder sb;
	private Thermometer publisher;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_testmain);

		initEasylink = (Button) findViewById(R.id.initEasyLink);
		udpResult = (TextView) findViewById(R.id.udpResult);

		text = (TextView) findViewById(R.id.textView1);
		scanResult = (TextView) findViewById(R.id.scanresult);
		button = (Button) findViewById(R.id.button1);
		scanQR = (Button) findViewById(R.id.scanqrcode);
		sendLayout = (LinearLayout) findViewById(R.id.sendlayout);
		mtext = (EditText) findViewById(R.id.mtext);
		sendText = (Button) findViewById(R.id.sendtext);
		sb = new StringBuilder();
		updateButton();

		publisher = Thermometer.getInstance(getApplicationContext());

	}

	@Override
	protected void onResume() {
		super.onResume();
		updateButton();
		registerReceiver(receiver, new IntentFilter(PushCallback.IMAction));
		
	}

	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(receiver);
	}

	private void updateButton() {
		if (serviceIsRunning()) {
			sendLayout.setVisibility(View.VISIBLE);
			button.setText("Stop Service");
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					button.setText("Start Service");
					stopBlackIceService();
					updateButton();
				}
			});

		} else {
			sendLayout.setVisibility(View.INVISIBLE);
			button.setText("Start Service");
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					if (getTopic().isEmpty()) {
						UIHandler.obtainMessage(TOASTMSG,"请先绑定您的水壶").sendToTarget();
					}
					button.setText("Stop Service");
					startBlackIceService();
					updateButton();
				}
			});
		}
		initEasylink.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), EasyLink.class);
				startActivityForResult(intent, UDP_REQUEST);
			}
		});

		scanQR.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ScanQRCode.class);
				startActivityForResult(intent, SCANQR_REQUEST);
			}
		});

		sendText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String str = mtext.getText().toString();
				if (!str.isEmpty()) {
					publisher.sendControlText(str);
					mtext.setText("");
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
//		if (requestCode == SCANQR_REQUEST && resultCode == RESULT_OK) {
//			String str = data.getStringExtra(GlobalConfig.SCANRESULT);
//			String s = ":";
//			String delete = str.replace(s, "");
//			scanResult.setText("扫描二维码结果=  " + delete);
//			System.out.println("--------delete----->" + delete);
//			GlobalConfig.topic = delete.replace("success", "");
//		}
//		if (requestCode == UDP_REQUEST && resultCode == RESULT_OK) {
//			String str = data.getStringExtra(GlobalConfig.UDPRESULT);
//			byte[] b = Base64.decode(str);
//			String decodeStr = new String(b);
//
//			udpResult.setText("广播接收结果=  " + decodeStr);
//
//			if (GlobalConfig.topic.equals(decodeStr.replace("success", ""))) {
//				Toast.makeText(getApplicationContext(),
//						"mac address matched,now can start mqtt",
//						Toast.LENGTH_LONG).show();
//				;
//
//			} else {
//				Toast.makeText(getApplicationContext(),
//						"mac address not matched,scan and configure again",
//						Toast.LENGTH_LONG).show();
//				;
//			}
//		}
	}

	private void startBlackIceService() {
		if (NetworkStatusUtil.isConnected(getApplicationContext())) {
			final Intent intent = new Intent(this, MQTTService.class);
			startService(intent);
		} else {
			UIHandler.obtainMessage(TOASTMSG, "请检查网络").sendToTarget();
		}
	}

	private void stopBlackIceService() {
		if (NetworkStatusUtil.isConnected(getApplicationContext())) {
			final Intent intent = new Intent(this, MQTTService.class);
			stopService(intent);
		} else {
			UIHandler.obtainMessage(TOASTMSG, "请检查网络").sendToTarget();
		}
	}

	private boolean serviceIsRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (SERVICE_CLASSNAME.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				ChannelObject obj = (ChannelObject) intent
						.getSerializableExtra("data");
				if (obj.getDataType() == ChannelObject.SEND) {
					sb.append("SEND:     ");
				} else {
					sb.append("RECEIVE:  ");
				}
				sb.append(new String(obj.getData()) + "\n");
				updateUI();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	protected void updateUI() {
		text.setText(sb.toString());
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}

}
